package com.pospi.xstore.ui.count;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.lany.sp.SPHelper;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.pospi.xstore.App;
import com.pospi.xstore.R;
import com.pospi.xstore.dao.GoodsDao;
import com.pospi.xstore.dialog.WaitingDialog;
import com.pospi.xstore.dto.CountBeen;
import com.pospi.xstore.dto.GoodsDto;
import com.pospi.xstore.greendao.CountBeenDao;
import com.pospi.xstore.http.LoadServer;
import com.pospi.xstore.ui.base.BaseActivity;
import com.pospi.xstore.util.Api;
import com.pospi.xstore.util.GetData;
import com.pospi.xstore.util.SaveOrderInfo;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by acer on 2018/6/20.
 */

public class CountListActivity extends BaseActivity {
    @Bind(R.id.counts_list)
    ListView mListView;
    @Bind(R.id.tv_count_date)
    TextView tv_count_date;
    @Bind(R.id.counts_up)
    TextView counts_up;
    private String time;
    private List<CountBeen> mCountBeens = new ArrayList<>();
    private CountBeenDao dao;
    private CountAdapter adapter;
    private int num;
    private String hg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_countlist);
        ButterKnife.bind(this);
        setTitle("盘点列表");
        setMenuImage(R.drawable.add);
        time = getIntent().getStringExtra("date");
        hg = getIntent().getStringExtra("hg");
        tv_count_date.setText(time);
        dao = App.getInstance().getDaoSession().getCountBeenDao();
        GoodsDao goodsDao = new GoodsDao(this);
        num = goodsDao.findGoodsNum();
        init();
    }

    private void init() {
        counts_up.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!checkNoUpdate()) {
                    Toast.makeText(CountListActivity.this, "已全部上传", Toast.LENGTH_SHORT).show();
                    return;
                }
                //开始上传
                showDialog("上传中...");
                for (CountBeen countBeen : mCountBeens) {
                    if (countBeen.getMCountSatus().equals("n")) {
                        upToServer(countBeen);
                    }
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(5000);
                            closeDialog();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(CountListActivity.this, "成功条数:"+suNum, Toast.LENGTH_SHORT).show();
                                }
                            });

                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();

            }
        });

        adapter = new CountAdapter();
        mListView.setAdapter(adapter);
        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                final int position = i;
                AlertDialog.Builder builder = new AlertDialog.Builder(CountListActivity.this);
                builder.setTitle("提示");
                builder.setMessage("是否删除该盘点单？");
                builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        delete(position);
                    }
                });
                builder.setNegativeButton("否", null);
                builder.show();
                return false;
            }
        });
        loadData();


    }

    private boolean checkNoUpdate() {
        for (CountBeen countBeen : mCountBeens) {
            if (countBeen.getMCountSatus().equals("n")) {
                return true;
            }
        }
        return false;
    }

    private Dialog waitingDialog;
    public void showDialog(String msg) {
        if (waitingDialog == null) {
            waitingDialog = WaitingDialog.createLoadingDialog(this, msg);
            waitingDialog.show();
        }
    }

    public void closeDialog() {
        if (waitingDialog != null) {
            waitingDialog.dismiss();
            waitingDialog = null;
        }
    }
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    closeDialog();
                    break;
                case 2:
                    closeDialog();
                    break;

            }

        }
    };

    private int suNum;
    private void upToServer(final CountBeen been) {
        List<GoodsDto> mList = SaveOrderInfo.changeToList(been.getMDetail());
        JSONArray array = new JSONArray();
        for (GoodsDto dto : mList) {
            JSONObject object = new JSONObject();
            try {
                object.put("goodsid", dto.getSid());
                object.put("sl", dto.getNum());
                array.put(object);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        RequestParams params = new RequestParams();
        params.put("id", SPHelper.getInstance().getString(CountsActivity.COUNTS_ID));
        params.put("date", time);
        params.put("hjh", hg);
        params.put("goods", array.toString());
        Log.i("data", params.toString());
        LoadServer.getConnect(this, Api.SYNC_COUNTS_UP, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                try {
                    Log.i("counst", new String(bytes));
                    JSONObject object = new JSONObject(new String(bytes));
                    if (object.getString("code").equals("1")) {
                        upStaus(been);
                        suNum++;
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
            }
        });

    }
    private void upStaus(CountBeen been){
        CountBeen countBeen = dao.queryBuilder().where(CountBeenDao.Properties.MId.eq(been.getMId())).unique();
        if (countBeen != null) {
            countBeen.setMCountSatus("y");
            dao.update(countBeen);
        }
        been.setMCountSatus("y");
        adapter.notifyDataSetChanged();
    }

    private void delete(int i) {
        CountBeen countBeen = dao.queryBuilder().where(CountBeenDao.Properties.MId.eq(mCountBeens.get(i).getMId())).unique();
        if (countBeen != null) {
            dao.delete(countBeen);
        }
        mCountBeens.remove(i);
        adapter.notifyDataSetChanged();

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        loadData();
    }

    private void loadData() {
        String shopId = getSharedPreferences("StoreMessage", Context.MODE_PRIVATE).getString("Id", "");
        mCountBeens.clear();
        List<CountBeen> beens = dao.queryBuilder().where(CountBeenDao.Properties.MCountDate.eq(time),CountBeenDao.Properties.MShopId.eq(shopId)).list();
        for (CountBeen been : beens) {
            mCountBeens.add(been);
        }
        adapter.notifyDataSetChanged();
    }


    @Override
    public void onMenuClick(View view) {
        super.onMenuClick(view);
        Intent intent = new Intent(this, CountActivity.class);
        intent.putExtra("date", time);
        startActivity(intent);

    }
    private class CountAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return mCountBeens.size();
        }

        @Override
        public Object getItem(int i) {
            return mCountBeens.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            Holder holder;
            if (view == null) {
                holder = new Holder();
                view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.counlist_item, null);
                holder.tv_sid = (TextView) view.findViewById(R.id.tv_count_sid);
                holder.tv_countsNum = (TextView) view.findViewById(R.id.tv_count_number);
                holder.tv_countType = (TextView) view.findViewById(R.id.tv_count_type);
                holder.tv_countStatus = (TextView) view.findViewById(R.id.tv_count_status);
                holder.tv_date = (TextView) view.findViewById(R.id.tv_count_time);
                view.setTag(holder);

            } else {
                holder = (Holder) view.getTag();
            }
            CountBeen been = mCountBeens.get(i);
            holder.tv_sid.setText(been.getMId());
            holder.tv_countsNum.setText(been.getMCountNum()+"/"+num);
            holder.tv_countType.setText(been.getMCountType());
            holder.tv_countStatus.setText(been.getMCountSatus().equals("n") ? "未上传" : "已上传");
            holder.tv_date.setText(been.getMTime());
            return view;
        }

    }
    class Holder{
        TextView tv_sid;
        TextView tv_date;
        TextView tv_countsNum;
        TextView tv_countsTotal;
        TextView tv_countStatus;
        TextView tv_countType;
    }

}
